package com.xy.xyaiagent.app;

import com.alibaba.cloud.ai.dashscope.api.DashScopeAgentApi;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.xy.xyaiagent.advisor.MyLoggerAdvisor;
import com.xy.xyaiagent.chatmemory.FileBasedChatMemory;
import com.xy.xyaiagent.rag.QueryRewriter;
import com.xy.xyaiagent.rag.WriteAppRagCustomAdvisorFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class writeApp {

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "你是一个专业的小红书内容创作者，擅长用通俗、有代入感、易共鸣的语言撰写文案。请根据以下要求生成一篇小红书风格的文案：\n" +
            "\n" +
            "【写作要求】\n" +
            "- 目标读者：20-35岁，主要是女性用户，追求品质生活、情绪价值或实用干货。\n" +
            "- 语气风格：真诚自然，像朋友聊天，适度使用表情符号（如✨、\uD83C\uDF38、\uD83E\uDEF6），带有轻微情绪起伏（比如惊喜、感动、共鸣）。\n" +
            "- 结构安排：\n" +
            "  1. 开头三行内抓住眼球（提炼出亮点/痛点/反转/好奇心）\n" +
            "  2. 中间细节生动，加入真实感受、亲测体验、对比变化、情绪波动。\n" +
            "  3. 结尾引导互动，如“姐妹们有没有同款体验？”、“快来评论区聊聊吧～”\n" +
            "- 内容建议：多用口语化表达，少用长句，适度断句，注意排版留白，方便手机阅读。\n" +
            "- 可以根据不同内容（如护肤、美妆、穿搭、旅游、美食、健身、学习成长等）选择合适的风格。\n" +
            "\n" +
            "【文案主题】\n" +
            "{请根据实际输入主题，比如：推荐一款平价又好用的防晒霜 / 三亚小众旅行攻略 / 怎么坚持健身三个月改变身材等}\n" +
            "\n" +
            "【补充信息】\n" +
            "- 产品/地点/经历亮点\n" +
            "- 亲测心得或转变前后对比\n" +
            "- 想要突出什么核心卖点（如平价、冷门好用、显著改变、懒人必备、超级治愈等）\n" +
            "\n" +
            "请按照以上要求输出小红书风格的完整文案。\n";

    /**
     * 初始化对话模型
     * @param dashscopeChatModel
     */
    public writeApp(ChatModel dashscopeChatModel) {
        // 初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
        // 初始化基于文件的对话记忆
        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);

        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        new MyLoggerAdvisor() // 日志记录
                )
                .build();
    }

    /**
     * AI 基础对话（支持多轮对话记忆功能）
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
//                .advisors(new MyLoggerAdvisor())
                .call()
                .chatResponse();
        String content = null;
        if (response != null) {
            content = response.getResult().getOutput().getText();
        }
        return content;
    }


    record WriteReport(String title, List<String> content){

    }

    /**
     * AI 报告功能 演示结构化输出
     * @param message
     * @param chatId
     * @return
     */
    public WriteReport doChatWithReport(String message, String chatId) {
        WriteReport writeReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话需要生成报告，标题为小红书主题名，内容为如何发布和监控流量")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(WriteReport.class);
//        log.info("writeReport: {}", writeReport);
        return writeReport;
    }

    @Resource
    private VectorStore pgvectorVectorStore;


    @Resource
    private QueryRewriter queryRewriter;

    /**
     * AI RAG 对话（支持多轮对话记忆功能,以及基于 RAG 知识库的对话）
     * @param message
     * @param chatId
     * @return
     */
    public String doRagChat(String message, String chatId) {
        String reMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse response = chatClient
                .prompt()
                .user(reMessage)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
//                .advisors(new MyLoggerAdvisor())
                .advisors(new QuestionAnswerAdvisor(pgvectorVectorStore))
//                .advisors(
//                        WriteAppRagCustomAdvisorFactory.createWriteAppRagCustomAdvisor(
//                                pgvectorVectorStore, "xiaohongshu_templates.md"
//                        )
//                )
                .call()
                .chatResponse();
        String content = null;
        if (response != null) {
            content = response.getResult().getOutput().getText();
        }
        return content;
    }

    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
//                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        return content;
    }
    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    public String doChatWithMcp(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        return content;
    }

}
